const puppeteer = require("puppeteer-extra");
const RecaptchaPlugin = require("puppeteer-extra-plugin-recaptcha");
const moment = require("moment");

const { createMobile, config } = require("../../../common/mobile");
const {
  info,
  saveFile,
  logging,
  timeout,
  reporter
} = require("../../../common/util");

puppeteer.use(
  RecaptchaPlugin({
    provider: {
      id: "2captcha",
      token: "2a52262e19b018b6790edd79ed20dc4d"
    },
    visualFeedback: true // 紫色：检测到，绿色：破解成功
  })
);

const name = "thm";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/th/thm/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);

(async () => {
  const browser = await puppeteer.launch(config);
  const page = await browser.newPage();

  const m = await createMobile(page);

  m._page.on("response", response => {
    let url = response.url();
    let status = response.status();

    if (url.startsWith("http")) {
      logger.info(`${response.request().method()}`, status, url);
    }

    // todo 改为truemove成功页面
    if (url.startsWith("https://services.dimoco.at/dcb/AT/mobilkom/redir")) {
      r.s("success");
    }

    if (url.startsWith("http://google.com")) {
      r.w("failure", url);
      m.close();
    }
  });

  //开始
  try {
    r.i("start");

    logger.info("start");

    await m.get(`https://mb-npltfpro.com/?a=96375&c=202863`);
    // await m.get(`http://dat.abfunny.com/dm/at/lp?track=2863251`);

    //等待页面加载完成
    await m._page.waitForSelector("#submit", { timeout });

    //保存页面
    logger.info("save1");

    // 点击去下一页
    await m.tapElement("#submit");
    // document.getElementById("submit").dispatchEvent(new Event("touchstart"));

    logger.info("page1 click");

    // await m._page.waitForNavigation({ timeout });

    logger.info("start captcha");

    await m._page.screenshot({ path: "start_th_captcha.png", fullPage: true });
    saveFile(`${logdir}/before.html`, await m._page.content());
    // recaptcha
    await m._page.solveRecaptchas();

    await m._page.screenshot({ path: "end_th_captcha.png", fullPage: true });
    saveFile(`${logdir}/after.html`, await m._page.content());

    logger.info("end captcha");

    await m._page.waitForSelector(`input[class='captcha-confirm']`);
    await m._page.screenshot({ path: "after_th_captcha.png", fullPage: true });
    await m._page.click(`input[class='captcha-confirm']`);

    logger.info("submit");
    await m._page.waitForNavigation({ timeout });

    logger.info("end");
    r.i("end");
  } catch (e) {
    saveFile(`${logdir}/error.html`, await m._page.content());
    r.e(e + "");
    logger.error(e);
  } finally {
    await m.close();
  }
  await browser.close();
})();
